#include <iostream>

using std::endl;
using std::cout;

class myClass
{
public:
	myClass()
	{
		cout << "construct" << endl;
	}
	myClass(const myClass& rhs)
	{
		cout << "copy construct" << endl;
	}
	myClass(myClass&& rhs)
	{
		cout << "move consturct" << endl;
	}
	~myClass()
	{
		cout << "desctruct" << endl;
	}
};

myClass func1(int n) {
	myClass mc1, mc2;
    //通过分支屏蔽NRVO, 此时会移动实际需要返回的值。
    if(n&0x1) return mc1;
    else return mc2; 
}

myClass func2(int n) {
	myClass mc1, mc2;
    cout << "&(n&0x1 ?mc1: mc2): " << &(n&0x1 ?mc1: mc2) << endl;
    //通过分支屏蔽NRVO, 但由于?:相当于返回左值引用的函数, 因此会对实际返回值进行拷贝
	return n&0x1 ?mc1: mc2; 
}

myClass func3() {
	myClass mc;
    auto &r = mc;
    //这里返回的局部变量的引用，不能完全等同于局部变量，此时不会发生NRVO, 并且由
    //于是左值引用，只能触发拷贝构造函数
    return r;
}

myClass func4() {
    auto &&r = myClass();
    return r; //同返回局部变量的左值引用：拷贝构造
}

myClass func5(myClass mc) {
    cout << "calling func5(myClass)..." << endl;
    return mc; //移动构造
}
  
myClass func6(myClass &&mc) {
    return mc; //拷贝构造
}
 
myClass func7() {
    static myClass mcs;
    return mcs; //拷贝构造
}
 
myClass &func8(myClass &&mc) {
    return mc; //返回mc地址，不安全(返回即析构)
} 
  
int main() {
    myClass mc;
    cout << "Test start..." << endl;    
	func1(1);
    cout << "test flag1..." << endl;    
	func2(2);
    cout << "test flag2..." << endl;    
	func3();
    cout << "test flag3..." << endl;    
	func4();
    cout << "test flag4..." << endl;    
	func5(myClass());
    cout << "test flag5..." << endl;    
	func6(myClass());
    cout << "test flag6..." << endl;    
	func7();
    cout << "test flag7..." << endl;    
	func8(myClass());
    cout << "test flag8..." << endl;    
      
    return 0;   
}


